﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FrameworkQ.ObjectSpace;
using FrameworkQ.ObjectSpace.Data.SqlObjects;

/// <summary>
/// Summary description for FoodValueFacade
/// </summary>
public class FoodValueFacade
{
	public FoodValueFacade()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    /*
    public void BuildComplexFoodDB()
    {
        Database db = new Database();
        if (!db.IsStorageReady(typeof(ComplexFood)))
        {
            db.CreateStorage(typeof(ComplexFood));
        }
        if (!db.IsStorageReady(typeof(ComplexFoodItem)))
        {
            db.CreateStorage(typeof(ComplexFoodItem));
        }

    }*/

    public List<ComplexFood> GetConfigs ()
    {
        Database db = new Database();
        return db.SelectAll<ComplexFood>();
    }

    public List<FoodValue> GetAllValues()
    {
        Database db = new Database();
        return db.SelectAll<FoodValue>();
    }

    public FoodValue GetFoodValue(int foodcode)
    {
        Database db = new Database();
        return db.Select<FoodValue> (foodcode);
    }

    public void SaveModel(SelectionModel model, string text)
    {
        Database db = new Database();
        ComplexFood cf = new ComplexFood() {FoodName = text};
        cf.ComplexFoodID = db.Insert(cf);

        foreach (SelectionItem item in model.SelectedItems)
        {
            ComplexFoodItem cfi = new ComplexFoodItem()
                                      {
                                          ComplexFoodItemID = cf.ComplexFoodID,
                                          FoodCode = item.FoodCode,
                                          Amount = item.Amount
                                      };
            db.Insert(cfi);
        }
    }

    public SelectionModel LoadModel ( string foodName)
    {
        SelectionModel m = null;
        using (Database db = new Database())
        {

            var result = db.SelectBy<ComplexFood>(string.Format("foodName='{0}'", foodName), "foodname");
            
            if (result.Count>0)
            {
                ComplexFood food = result[0];
                m = new SelectionModel();
                var items = db.SelectBy<ComplexFoodItem>(string.Format("ComplexFoodItemID={0}", food.ComplexFoodID),
                                                         "FoodCode");
                foreach (var complexFoodItem in items )
                {
                    m.SelectedItems.Add(new SelectionItem() {Amount = complexFoodItem.Amount, FoodCode = complexFoodItem.FoodCode} );
                }
            }
        }
        return m;
    }
}